package com.jvm.jdbc.demo2;

import com.jvm.jdbc.util.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * jdbcTemplate实现类
 * </p>
 *
 * @author qingshan
 * @since 2020-10-11 15:33
 */
public class JdbcTemplateUserImpl extends JdbcTemplate {
    /**
     * 子类负责实现
     * 在doInStatement()方法中，对ResultSet进行了遍历，最后并返回
     * @param rs 此方法不是由子类调用的，而是由父类调用，并把ResultSet传递给子类的
     * @return
     */
    @Override
    protected Object doInStatement(ResultSet rs) {
        List<User> userList = new ArrayList<User>();

        try {
            User user = null;
            while (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("user_name"));
                user.setAge(rs.getInt("age"));
                user.setSex(rs.getString("sex"));
                userList.add(user);
            }
            return userList;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String sql = "select * from user";
        JdbcTemplate jt = new JdbcTemplateUserImpl();
        try {
            List<User> userList = (List<User>) jt.execute(sql);
            System.out.println(userList.size());
            for (User user: userList) {
                System.out.println(user.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
